package com.kangjia.general.dao;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Projections;
import org.springframework.beans.factory.annotation.Autowired;

import com.kangjia.general.dao.query.ConditionBuilder;
import com.kangjia.general.dao.query.Param;
import com.kangjia.general.dao.query.order.Order;
import com.kangjia.general.dao.query.order.OrderBuilder;

/**
 * dao抽象类,获取sessionFactory, session
 * 
 * @author sunshulin
 *
 */
public abstract class AbstractDao {

	@Autowired
	private SessionFactory sessionFactory;
	
	/**
	 * 构建查询条件
	 * 
	 * @param criteria
	 * @param params
	 */
	protected void builderCondition(Criteria criteria, List<Param<?>> params) {
		ConditionBuilder builder = new ConditionBuilder(criteria);
		for (Param<?> param : params) {
			builder.builder(param);
		}
	}

	/**
	 * 统计记录数
	 * 
	 * @param criteria
	 * @return
	 */
	protected Integer getTotal(Criteria criteria) {
		criteria.setProjection(Projections.rowCount());
		Object object = criteria.uniqueResult();
		if (object != null) {
			return Integer.parseInt(String.valueOf(object));
		}
		return 0;
	}
	
	protected void builderOrder(Criteria criteria, List<Order> orders) {
		OrderBuilder builder = new OrderBuilder(criteria);
		for (Order order : orders) {
			builder.builder(order);
		}
	}

	protected Session getSession() {
		return sessionFactory.getCurrentSession();
	}
}
